import { Form, Input, Modal, Select } from 'antd';
import { RoleData } from '@/types/sys';
import { addRole, updateRole } from '@/api/sys';
const Dialog = (props: {
  open: boolean;
  title: string;
  setOpen: (open: boolean) => void;
  record: RoleData | null;
  onSuccess: () => void;
}) => {
  const { open, title, setOpen, record,onSuccess } = props;
  const [form] = Form.useForm();
  useEffect(() => {
    if (!open) {
      form.resetFields(); // 关闭对话框时重置表单
    } else if (record) {
      form.setFieldsValue(record);
    } else {
      form.setFieldsValue({ status: '1' });
    }
    // 移除 else 分支，这样当 record 为 null 时不会重置表单
  }, [open, record, form]);
  const onFinish = async (values: RoleData) => {

    if (record?.id) {
      const data = {
        id: record.id,
        ...values,
      };

      const result = await updateRole(data);
      if (!result) return;
      console.log(result);
    } else {
      console.log('新增', values);
      const result = await addRole(values);
      console.log(result);
    }
    onSuccess();
    setOpen(false);
  };
  const onOk = () => {
    form.validateFields().then((values: RoleData) => {
      onFinish(values);
    });
    // setOpen(false);
  };
  const onCancel = () => {
    form.resetFields(); // 重置表单
    setOpen(false);
  };
  return (
    <Modal title={title} open={open} onOk={onOk} onCancel={onCancel}>
      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
        <Form.Item
          label="角色名称"
          name="role_name"
          rules={[{ required: true, message: '请输入角色名称' }]}
        >
          <Input placeholder="请输入角色名称" />
        </Form.Item>
        <Form.Item label="角色描述" name="remark">
          <Input placeholder="请输入角色描述" />
        </Form.Item>
        <Form.Item label="状态" name="status">
          <Select placeholder="请选择状态">
            <Select.Option value="1">启用</Select.Option>
            <Select.Option value="0">禁用</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default Dialog;
